import { Button, Input, Result } from 'antd'
import Form from 'antd/lib/form/Form'
import FormItem from 'antd/lib/form/FormItem'
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Redirect } from 'react-router-dom'
import { isAuth } from '../../helpers/auth'
import { signin, SigninPayload } from '../../store/actions/auth.action'
import { AppState } from '../../store/reducers'
import { AuthState } from '../../store/reducers/auth.reducer'
import Layout from './Layout'

const Signin = () => {
  const dispatch = useDispatch()
  const onFinish = (value:SigninPayload) => {
    console.log(value)
    dispatch(signin(value))
  }
  //1、获取登录结果
  const authState = useSelector<AppState, AuthState>(state => state.auth)
  //2、登录失败，显示错误信息
  const showError = () => {
    if (authState.signin.loaded && !authState.signin.success) {
      return (
        <Result
          title="登录失败"
          subTitle={authState.signin.message}
          status="warning"
        />
      )
    }
  }
  //3、登录成功，根据角色跳转到对应的dashboard页面
  const showSuccess = () => {
    console.log('showSuccess')
    console.log(authState)
    if (authState.signin.loaded && authState.signin.success) {
      const auth = isAuth()
      console.log(auth)

      if(auth) {
        const {
          user:
          {
            role
          }
        } = auth
        console.log(role)

        if (role === 0) {
          return <Redirect to="/user/dashboard" />
        }else {
          return <Redirect to="/admin/dashboard" />
        }
      }
    }

  }
  const signinForm = () => (
      <Form onFinish={onFinish} initialValues={{password: '123456', email: 'testemail@163.com' }}>
        <FormItem label="昵称" name="email">
          <Input />
        </FormItem>
        <FormItem label="密码" name="password">
          <Input.Password />
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">登录</Button>
        </FormItem>
      </Form>
  )
  return (
    <Layout title="拉钩登录" subTitle="拉钩登录">
      {showError()}
      {showSuccess()}
      {signinForm()}
    </Layout>
  )
}

export default Signin